// object

$.prototype.parametro = function() {
	x = this[0];
	var aux = [];
	for ( var obj in x) {
		if (!$.isFunction(x[obj]))
			aux.push(obj + '=' + x[obj]);
	}

	for ( var i = 0; i < arguments.length; i++) {
		aux.push($(arguments[i]).parametro());
	}

	return aux.join('&');
};

// utilitarios para arrays

Array.prototype.map = function(func) {
	return $.map(this, func);
};

Array.prototype.unique = function(func) {
	var a = this;
	    var p, i, j;
	    for(i = a.length; i;){
	        for(p = --i; p > 0;)
	            if(func(a[i]) === func(a[--p])){
	                for(j = p; --p && func(a[i]) === func(a[p]););
	                i -= a.splice(p + 1, j - p).length;
	            }
	    }
	return a;
};

Array.prototype.ordena = function(func) {
	collection = this;
	for ( var j = 1; j < collection.length; j++) {
		var key = collection[j];
		var i = j - 1;

		while (i >= 0 && func(collection[i], key)) {
			collection[i + 1] = collection[i];
			i = i - 1;
		}

		collection[i + 1] = key;
	}
	return this;
};

// utilitarios gerais
log = function(mensagem) {

	if (mensagem instanceof Object) {
		console.log(mensagem);
		return;
	}

	try {
		gerando.uma.exception = +45;
	} catch (e) {
		var stack = e.stack.split('\n')[2];
		var line = stack.split('/');
		line = line[line.length - 1];
		console.log("[" + line + "] " + mensagem);
	}

};

// view Utils

// append de links em tabelas

$.prototype.addLink = function(title, link) {
	if (this[0].tagName == "TABLE") {
		this.append('<tr><td><a href="' + link + '">' + title
				+ '</a></td></tr>');
	}
};

// variaveis

function isDefined(variable) {
	return (typeof (window[variable]) == "undefined") ? false : true;
}

// gerador de url
url = function(tela) {

	var toVillage = village;
	var toMode = '';
	var parametros = '';

	for ( var i = 1; i < arguments.length; i++) {
		var it = arguments[i];
		var auxVila = parseInt(it);
		if (it.search('=') != -1) { // 'e parametro
			parametros += '&' + it;
		} else if (isNaN(auxVila)) { // nao e numero
			toMode = "&mode=" + it;
		} else {
			toVillage = auxVila;
		}
	}

	return pageUrl.match(/.*\?/) + "screen=" + tela + "&village=" + toVillage
			+ toMode + parametros;
};

// ajax

ajax = function(actions) {
	mudanca = function() {
		switch (req.readyState) {
		case (1):
			if (actions.loading != null)
				actions.loading();
			break;
		case (4):
			if (actions.load != null)
				actions.load(req.responseText);
			if (actions.complete != null)
				actions.complete();
			break;
		}
	};
	actions.async = actions.async == null ? true : actions.async;

	actions.method = actions.method == null ? "GET" : actions.method;
	actions.parametros = actions.parametros == null ? actions.parametros = null
			: actions.parametros;
	var req = new XMLHttpRequest();

	req.open(actions.method, actions.url, actions.async);
	req.onreadystatechange = mudanca;

	if (actions.method == "POST") {
		req.setRequestHeader("Content-type",
				"application/x-www-form-urlencoded");
	}

	req.send(actions.parametros);
};

// utils matematicos
int = function(x) {
	return parseInt(x);
};

// gerador de tabela
table = function(matrix,style) {
	if (style == null)
		style = '';
	else style = 'style="'+style+'"';
	
	var out = '<table class="vis nowrap" '+style+'>';
	for ( var i = 0; i < matrix.length; i++) {
		out += "<tr>";
		for ( var j = 0; j < matrix[i].length; j++) {
			if (i == 0)
				out += "<th>" + matrix[i][j] + "</th>";
			else
				out += "<td>" + matrix[i][j] + "</td>";
		}
		out += "</tr>";
	}
	out += "</table>";
	return out;
};

// clonador
function clone(obj){

    if(obj == null || typeof(obj) != 'object')
        return obj;

    var temp = obj.constructor(); // changed

    for(var key in obj){
        temp[key] = clone(obj[key]);
    }
    return temp;
}

// localStorage

save = function(name,val){
	localStorage[name] = JSON.stringify(val);
}

load = function(name){
	eval("var x= "+localStorage[name]);
	return x;
}